import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/mrp_production_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/mrp_production.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/odoo/mrp_production/mrp_production_dialog.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:quiver/strings.dart';

class MrpProductionList extends StatefulWidget {
  MrpProductionList({Key? key}) : super(key: key);

  @override
  _MrpProductionListState createState() => _MrpProductionListState();
}

class _MrpProductionListState extends State<MrpProductionList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  MrpProduction mrpProduction = MrpProduction();
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      // _query();
    });
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            width: 140,
            label: '生产单号',
            value: mrpProduction.productionorderno,
            onSaved: (v) {
              mrpProduction.productionorderno = v;
            },
          ),
          CryInput(
            width: 140,
            label: '批次号',
            value: mrpProduction.batchno,
            onSaved: (v) {
              mrpProduction.batchno = v;
            },
          ),
          CryInput(
            width: 140,
            label: '产品名称',
            value: mrpProduction.productId,
            onSaved: (v) {
              mrpProduction.productId = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('完成时间')),
        DataColumn(label: Text('当前位置')),
        DataColumn(label: Text('生产车间')),
        DataColumn(label: Text('完成数量')),
        DataColumn(label: Text('单位')),
        DataColumn(label: Text('生产单号')),
        DataColumn(label: Text('产品图号')),
        DataColumn(label: Text('产品名称')),
        DataColumn(label: Text('批次号')),
      ],
      getCells: (m) {
        MrpProduction mrpProduction = MrpProduction.fromMap(m);
        return [
          DataCell(Text(mrpProduction.reportdate ?? '--')),
          DataCell(Text(mrpProduction.stationId ?? '--')),
          DataCell(Text(mrpProduction.workshopId ?? '--')),
          DataCell(Text(mrpProduction.qualifiedquantity ?? '--')),
          DataCell(Text(mrpProduction.unit ?? '--')),
          DataCell(Text(mrpProduction.productionorderno ?? '--')),
          DataCell(Text(mrpProduction.defaultCode ?? '--')),
          DataCell(Text(mrpProduction.productId ?? '--')),
          DataCell(Text(mrpProduction.batchno ?? '--')),
        ];
      },
    );
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              isDisplayDesktop(context) ? form : Container(),
              Padding(
                padding: EdgeInsets.only(top: 24),
                child: isDisplayDesktop(context) ? buttonBar : Container(),
              )
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _reset() {
    mrpProduction = MrpProduction();
    formKey.currentState!.reset();
    tableKey.currentState?.pageTo(0);
    tableKey.currentState?.loadData(PageModel());
    // _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    if (isBlank(mrpProduction.productionorderno)) {
      CryUtils.message("请输入生产单号");
      return;
    }
    ResponseBodyApi responseBodyApi = await MrpProductionOdooApi.page(data: {
      "page": page,
      "domainList": mrpProduction.toDomainList(),
    });
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
    }
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: MrpProductionDialog(),
      ),
    ).then((v) {
      if (v != null) {
        mrpProduction = v;
        _query();
      }
    });
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
      ],
    );
  }
}
